package org.example.petsystem.service.impl;

import org.example.petsystem.entity.ResultBody;
import org.example.petsystem.mapper.AddressMapper;
import org.example.petsystem.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AddressServiceimpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public ResultBody getUserAddresses(Map<String, Object> params) {
        try {
            List<Map<String, Object>> addresses = addressMapper.getUserAddresses(params);
            return new ResultBody(200, "获取地址成功", addresses);
        } catch (Exception e) {
            return new ResultBody(500, "获取地址失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResultBody saveUserAddresses(Map<String, Object> params) {
        try {
            String userId = (String) params.get("userId");
            List<Map<String, Object>> addresses = (List<Map<String, Object>>) params.get("addresses");

            for (Map<String, Object> address : addresses) {
                Map<String, Object> addressParams = new HashMap<>();
                addressParams.put("userId", userId);
                addressParams.put("address", address.get("address"));

                // 处理isDefault
                String isDefault = address.get("isDefault").toString();
                addressParams.put("isDefault", isDefault);

                // 处理id
                Object idObj = address.get("id");
                String id;
                if (idObj == null || "".equals(idObj)) {
                    // 你可以选择报错，也可以自动生成
                    return new ResultBody(400, "id不能为空，请前端传入id");
                } else {
                    id = idObj.toString();
                }
                addressParams.put("id", id);

                // 判断数据库是否已存在该id，存在就update，不存在就insert
                Map<String, Object> exist = addressMapper.getAddressById(addressParams);
                if (exist == null) {
                    addressMapper.insertAddress(addressParams);
                } else {
                    addressMapper.updateAddress(addressParams);
                }

                // 如果是默认地址，重置其他地址为非默认
                if (isDefault.equals("true")) {
                    Map<String, Object> defaultParams = new HashMap<>();
                    defaultParams.put("userId", userId);
                    defaultParams.put("addressId", id);
                    addressMapper.resetOtherDefaultAddresses(defaultParams);
                }
            }

            // 返回最新地址列表
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("userId", userId);
            List<Map<String, Object>> updatedAddresses = addressMapper.getUserAddresses(queryParams);
            return new ResultBody(200, "地址保存成功", updatedAddresses);
        } catch (Exception e) {
            return new ResultBody(500, "地址保存失败：" + e.getMessage());
        }
    }

    @Override
    public ResultBody deleteAddress(Map<String, Object> params) {
        try {
            addressMapper.deleteAddress(params);
            return new ResultBody(200, "地址删除成功");
        } catch (Exception e) {
            return new ResultBody(500, "地址删除失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResultBody setDefaultAddress(Map<String, Object> params) {
        try {
            Object addressIdObj = params.get("addressId");
            String addressId;
            if (addressIdObj instanceof Integer) {
                addressId = String.valueOf(addressIdObj);
            } else if (addressIdObj instanceof String) {
                addressId = (String) addressIdObj;
            } else {
                return new ResultBody(400, "addressId类型错误");
            }

            Map<String, Object> defaultParams = new HashMap<>();
            defaultParams.put("addressId", addressId);
            addressMapper.setDefaultAddress(defaultParams);

            // 获取地址对应的用户ID
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("addressId", addressId);
            Map<String, Object> addressInfo = addressMapper.getAddressById(queryParams);

            if (addressInfo != null && addressInfo.containsKey("userId")) {
                String userId = String.valueOf(addressInfo.get("userId"));

                // 重置用户的其他地址为非默认
                Map<String, Object> resetParams = new HashMap<>();
                resetParams.put("userId", userId);
                resetParams.put("addressId", addressId);
                addressMapper.resetOtherDefaultAddresses(resetParams);
            }

            return new ResultBody(200, "默认地址设置成功");
        } catch (Exception e) {
            return new ResultBody(500, "设置默认地址失败：" + e.getMessage());
        }
    }
}